package com.action.boot.mongo.mongo_template.dao;

import com.action.boot.mongo.mongo_template.entity.BathUpdateOptions;
import com.action.boot.mongo.mongo_template.entity.BulkInfo;
import com.action.boot.mongo.mongo_template.entity.TestBath;
import com.action.boot.mongo.mongo_template.util.BathUpdateUtil;
import com.action.boot.mongo.mongo_template.util.BeanConvert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.BulkOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Wuxiang on 2017/11/3.
 */
@Component
public class BathUpdateDao {
    @Autowired
    MongoTemplate mongoTemplate;

    public int bathAdd(List<TestBath> testBaths) {
        mongoTemplate.insert(testBaths, TestBath.class);
        return testBaths.size();
    }

    public int bathUpdate(List<TestBath> testBaths) {
        List<BathUpdateOptions> list = new ArrayList<>();
        for (int i = 0; i < testBaths.size(); i++) {
            Update update = BeanConvert.beanToMongoUpdate(testBaths.get(i));
            Query query = new Query();
            query.addCriteria(Criteria.where("name").is(testBaths.get(i).getName()));
            list.add(new BathUpdateOptions(query, update, true, true));
        }
        int n = BathUpdateUtil.bathUpdate(mongoTemplate, TestBath.class, list);
        System.out.println("受影响的行数："+n);
        return n;
    }

    public int bulkAdd(List<BulkInfo> bulkInfos) {
        mongoTemplate.insert(bulkInfos, BulkInfo.class);
        return bulkInfos.size();
    }

    public int bulkUpdate(List<BulkInfo> bulkInfos) {
        BulkOperations operations = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, BulkInfo.class);
        for (BulkInfo info : bulkInfos) {
            Update update = BeanConvert.beanToMongoUpdate(info);
            Query query = new Query();
            query.addCriteria(Criteria.where("id").is(info.getId()));
            operations.upsert(query, update);
        }
        operations.execute();
        return bulkInfos.size();
    }
}
